from jinja2 import Environment, FileSystemLoader, StrictUndefined
from . import functions

def get_env(stream_mode=False):
    env = Environment(
        loader=FileSystemLoader('web/static'),
        undefined=StrictUndefined,
        trim_blocks=True,
        lstrip_blocks=True
    )
    env.filters['from_json'] = functions.from_json
    env.globals.update({
        'add': functions.add,
        'subtract': functions.subtract,
        'multiply': functions.multiply,
        'equal': functions.equal,
        'notequal': functions.notequal,
        'greater': functions.greater,
        'less': functions.less,
        'not': functions.not_,
        'contains': functions.contains,
        'strip': functions.strip,
        'append': functions.append,
        'dictget': functions.dictget,
        'condition': lambda expr, ctx=None: functions.condition(expr, ctx or {}),
        'gen': functions.gen,
        'gen_stream': functions.gen_stream,
        'from_json': functions.from_json,
    })
    return env

def render_template(template_code, context):
    env = get_env(stream_mode=False)
    template = env.from_string(template_code)
    print("DEBUG: template_code =", template_code)
    print("DEBUG: env.globals.keys() =", list(env.globals.keys()))
    result = template.render(**context)
    print("DEBUG: render result =", result)
    return result

def render_template_stream(template_code, context):
    env = get_env(stream_mode=True)
    template = env.from_string(template_code)
    # 直接用 Jinja2 的 generate 方法流式输出
    for chunk in template.generate(**context):
        yield chunk 